﻿using System;
using CommonUtils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace plasp.cookiea.com.Attributes
{
    public class CheckLoginAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            string url = filterContext.HttpContext.Request.Path.ToString();
            filterContext.HttpContext.Session.TryGetValue(StaticString.Token, out byte[] token);
            string sessionToken = token != null ? System.Text.Encoding.Default.GetString(token) : string.Empty;
            string cookieToken = filterContext.HttpContext.Request.Cookies[StaticString.Token];
            filterContext.HttpContext.Request.Cookies.TryGetValue(StaticString.Token, out string value);

            if (!string.IsNullOrEmpty(url) && !url.Contains("LoginAuth") &&
                (string.IsNullOrEmpty(sessionToken) || string.IsNullOrWhiteSpace(cookieToken) ||
                 sessionToken != cookieToken))
            {
                filterContext.Result = new RedirectResult("~/LoginAuth/Index");
            }
        }
    }
}
